<template>
  <div class="edit-post-container">
    <h2>编辑帖子</h2>
    <div v-if="post">
      <el-form @submit.prevent="savePost">
        <el-form-item label="标题">
          <el-input v-model="post.title" />
        </el-form-item>
        <el-form-item label="话题">
          <el-input v-model="post.topic" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="post.content" type="textarea" :rows="5" />
        </el-form-item>
        <el-button type="primary" native-type="submit">保存更改</el-button>
      </el-form>
    </div>

    <div v-else>
      数据加载中...
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from '../axios'
import type { Post } from '../types/Article'

const route = useRoute()
const router = useRouter()
const post = ref<Post | null>(null)
const id = parseInt(route.params.id as string)

const fetchPost = async () => {
  try {
    const response = await axios.get<Post>(`/api/posts/${id}`)
    post.value = response.data
  } catch (error) {
    console.error('获取帖子失败:', error)
  }
}

const savePost = async () => {
  try {
    await axios.put(`/api/posts/${id}`, post.value);
    alert('更新成功');

    // ✅ 新增：手动刷新帖子列表
    const userPostsRouteName = 'UserPosts'; // 假设你的路由名称为 UserPosts
    router.push({ name: userPostsRouteName }).then(() => {
      // 路由跳转完成后触发 loadPosts()
      const event = new Event('user-posts-refresh'); // 自定义事件
      window.dispatchEvent(event); // 触发全局事件通知刷新
    });

  } catch (error) {
    console.error('更新失败:', error);
    alert('更新失败，请重试');
  }
};
onMounted(fetchPost)
</script>